package cn.lanqiao.bigDate.web.controller;


import cn.lanqiao.bigDate.entity.sys.SysDept;
import cn.lanqiao.bigDate.entity.sys.SysMenu;
import cn.lanqiao.bigDate.entity.sys.SysRole;
import cn.lanqiao.bigDate.entity.sys.SysRoleMenu;
import cn.lanqiao.bigDate.reslut.Result;
import cn.lanqiao.bigDate.reslut.TreeNode;
import cn.lanqiao.bigDate.web.BaseController;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping(SysRoleController.BASE_URL)
public class SysRoleController extends BaseController {

    public static final String BASE_URL = "sysRole";

    /**
     * 页面跳转
     * @return  页面mav
     */
    @RequestMapping(value = "toIndex")
    public ModelAndView toIndex() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName(BASE_URL + "/index"); //指定路径
        return mav;
    }

    @RequestMapping(value = "test")
    public ModelAndView test() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName(BASE_URL + "/test"); //指定路径
        return mav;
    }

    /**
     * 分页查询
     * @return  分页结果
     */
    @GetMapping(value = "findSysRolePage")
    public IPage<SysRole> findByPage(Page<SysRole> page, String searchLike) {
        return sysRoleService.findByPage(page,searchLike);
    }

    /**
     * 查询所有数据
     * @return
     */
    @GetMapping(value = "findAllSysRole")
    public List<SysRole> findAll() {
        return sysRoleService.findAll();
    }

    /**
     * 按ID查询用户
     * @return  结果
     */
    @GetMapping(value = "findSysRoleOne")
    public SysRole findSysRoleOne(Long id) {
        return sysRoleService.findSysRoleOne(id);
    }


    /**
     * 修改用户信息
     * @param sysRole
     * @return
     */
    @PostMapping(value = "updateSysRole")
    public Result<String> updateSysRole(SysRole sysRole,String menuIds) {
        SysRoleMenu sysRoleMenu = new SysRoleMenu();
        Result<String> reslut = new Result();
        if (sysRole.getRoleName()==null || sysRole.getCreateBy()==null){
            reslut.setCode(500);
            reslut.setMsg("不能为空");
        }else{
            String[] split = menuIds.split(",");
            Boolean isSuccess = sysRoleService.updateSysRole(sysRole,split);
//            sysRoleMenu.setRoleId(sysRole.getId());
            if(isSuccess){
                reslut.setCode(200);
                reslut.setMsg("修改成功");
            }else{
                reslut.setCode(500);
                reslut.setMsg("修改失败");
            }
        }
        return reslut;
    }

    /**
     * 添加用户信息
     * @param sysRole
     * @return
     */
    @PostMapping(value = "saveSysRole")
    public Result<String> saveSysRole(SysRole sysRole,String menuIds) {
        SysRoleMenu sysRoleMenu = new SysRoleMenu();
        Result<String> reslut = new Result();
        if (sysRole.getRoleName()==null || sysRole.getCreateBy()==null) {
            reslut.setCode(500);
            reslut.setMsg("不能为空");
        }else {
            //将前端传回的json字符串分割转为数组
            String[] split = menuIds.split(",");
            //调用savaSysRole方法将数组中的数组存储到关联表中
            Boolean isSuccess = sysRoleService.saveSysRole(sysRole,split);
//            sysRoleMenu.setRoleId(sysRole.getId());
            if (isSuccess) {
                reslut.setCode(200);
                reslut.setMsg("添加成功");
            } else {
                reslut.setCode(500);
                reslut.setMsg("添加失败");
            }
        }
        return reslut;
    }

    /**
     * 按id删除
     * @param ids
     * @return
     */
    @RequestMapping(value = "deleteSysRole")
    public Result<String> deleteItem(String ids) {
        Result<String> reslut = new Result();
        Boolean isSuccess = sysRoleService.deleteSysRole(ids);
        if(isSuccess){
            reslut.setCode(200);
            reslut.setMsg("删除成功");
        }else{
            reslut.setCode(500);
            reslut.setMsg("删除失败");
        }
        return reslut;
    }


    /**
     * 查询出所有菜单
     * @return
     */
    @GetMapping(value = "findAllSysMenu")
    public Result<List<TreeNode>> findAllSysMenu(Long roleId) {
        Result<List<TreeNode>> result = new Result<>();
        List<TreeNode> list = sysMenuService.findAllSysMenu(roleId);
        if(list!=null){
            result.setData(list);
            result.setCode(200);
            result.setMsg("成功");
        }else{
            result.setCode(500);
            result.setMsg("失败");
        }
        return result;
    }

    /**
     * 按id查询菜单
     * @param id
     * @return
     */
    @GetMapping(value = "findSysMenuOne")
    public Result<SysMenu>  findSysMenuOne(Long id) {
        Result<SysMenu> result = new Result<>();
        SysMenu sm =  sysMenuService.findSysMenuOne(id);
        if(sm!=null){
            result.setData(sm);
            result.setCode(200);
            result.setMsg("成功");
        }else{
            result.setCode(500);
            result.setMsg("失败");
        }
        return result;
    }

    /**
     * 数据导出
     * @param response
     * @throws IOException
     * @throws ParseException
     */
    @RequestMapping("downloadExcel")
    public void outPutExcel (HttpServletResponse response) throws IOException {
        //每次写100行数据，刷新数据出缓存
        SXSSFWorkbook wb = new SXSSFWorkbook(100);
        Sheet sheet = wb.createSheet();
        //业务数据
        List<SysRole> list = sysRoleService.findAll();
        String[] titles = {"id","role_name","create_by","update_by","create_time","update_time","remark"};
        Row row = sheet.createRow(0);
        //设置第一行标题
        for (int i = 0; i < titles.length; i++) {
            String title = titles[i];
            Cell cell1 = row.createCell(i);
            cell1.setCellValue(title);
        }
        //格式化localDateTime类型的日期
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
        //导出数据
        for (int i = 0; i <list.size() ; i++) {
            Row rowData = sheet.createRow(i + 1);
            //实体类  通过实体类填写数据
            SysRole sysRole = list.get(i);
            //第一列 数据
            Cell cellDataA = rowData.createCell(0);
            cellDataA.setCellValue(sysRole.getId());
            //第二列 数据
            Cell cellDataB = rowData.createCell(1);
            cellDataB.setCellValue(sysRole.getRoleName());
            //第三列 数据
            Cell cellDataC = rowData.createCell(2);
            cellDataC.setCellValue(sysRole.getCreateBy());
            //第四列 数据
            Cell cellDataD = rowData.createCell(3);
            cellDataD.setCellValue(sysRole.getUpdateBy());
            //第五列 数据
            Cell cellDataE = rowData.createCell(4);
            if (null!=sysRole.getCreateTime()){
                String createTime = dateTimeFormatter.format(sysRole.getCreateTime());
                cellDataE.setCellValue(createTime);
            }
            //第六列 数据
            Cell cellDataF = rowData.createCell(5);
            if (null!=sysRole.getUpdateTime()){
                String updateTime = dateTimeFormatter.format(sysRole.getUpdateTime());
                cellDataF.setCellValue(updateTime);
            }
            //第七列 数据
            Cell cellDataG = rowData.createCell(6);
            cellDataG.setCellValue(sysRole.getRemark());
        }
        String fileName = "角色表.xlsx";
        response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
        wb.write(response.getOutputStream());
        wb.close();
    }


    /**
     * 导入数据
     * @param request
     * @return
     */
    @PostMapping(value = "importRoleExcel")
    public Result<String> importOrderData(HttpServletRequest request) {
        Result<String> result = new Result<>();
        if (!(request instanceof MultipartHttpServletRequest)) {
            result.setCode(200);
            return result;
        }
        try {
            List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file-2");
            for (MultipartFile file : files) {
                System.out.println("data:>>"+file.getName());
                String fileName = file.getOriginalFilename();
                long size = file.getSize();
                if (size == 0) {
                    result.setCode(500);
                    result.setMsg("文件为空");
                    return result;
                }
                String[] name = fileName.split("\\.");
                //默认为高级版excel
                int type = 1;
                if ("xls".equals(name[1])) {
                    type = 2;
                }
                List<SysRole> sheet1 = excelService.readExcelOfList(file.getInputStream(), "sheet1", SysRole.class);
                for (SysRole sysRole : sheet1) {
                    if (sysRole.getId()==null||sysRole.getRoleName()==null||sysRole.getCreateBy()==null||sysRole.getCreateTime()==null||sysRole.getUpdateBy()==null||sysRole.getUpdateTime()==null||sysRole.getRemark()==null){
                        continue;
                    }
                     sysRoleService.saveSysRole(sysRole);
                }
                System.out.println(sheet1);
            }
            result.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMsg(e.getMessage());
        }
        return result;
    }

}
